import React, { useState, useEffect } from "react";
import { withRouter } from "react-router-dom";
import { Layout, Menu } from "antd";
import axios from "axios";
import { connect } from "react-redux";
const { Sider } = Layout;
const { SubMenu } = Menu;

function SideMenu(props) {
  const [menu, setMenu] = useState([]);
  useEffect(() => {
    axios.get("/rights?_embed=children").then(({ data }) => {
      setMenu(data);
    });
  }, []);
  const {
    role: { rights }
  } = JSON.parse(localStorage.getItem("token"));
  const checkPagepermisson = item => {
    return item.pagepermisson === 1 && rights.includes(item.key);
  };
  function renderMenu(menuList) {
    return menuList.map(item => {
      if (item.children?.length > 0 && checkPagepermisson(item)) {
        return (
          <SubMenu key={item.key} title={item.title}>
            {renderMenu(item.children)}
          </SubMenu>
        );
      }
      return (
        checkPagepermisson(item) && (
          <Menu.Item
            key={item.key}
            onClick={() => props.history.push(item.key)}
          >
            {item.title}
          </Menu.Item>
        )
      );
    });
  }
  const selectedKey = [props.location.pathname];
  const openedKey = ["/" + props.location.pathname.split("/")[1]];
  return (
    <Sider trigger={null} collapsible collapsed={props.isCollapsed}>
      <div className="logo">全球新闻发布系统</div>
      <Menu
        theme="dark"
        mode="inline"
        selectedKeys={selectedKey}
        defaultOpenKeys={openedKey}
      >
        {renderMenu(menu)}
      </Menu>
    </Sider>
  );
}
const mapStateToProps = ({ collapsed: { isCollapsed } }) => {
  return {
    isCollapsed
  };
};
export default connect(mapStateToProps)(withRouter(SideMenu));
